<template>
  <!-- 编辑弹出框 -->
  <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%" top="30vh">
    <el-form ref="dataForm" :model="dataForm" label-width="70px">
      <el-form-item label="ID"><el-input v-model="dataForm.id" :disabled="true"></el-input></el-form-item>
      <el-form-item label="名称"><el-input v-model="dataForm.name"></el-input></el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button size="medium" @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" size="medium" @click="dataFormSubmit">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import * as CategoryAPI from '@/api/category.js';

export default {
  name: 'categoryEdit',
  data() {
    return {
      dialogVisible: false,
      dataForm: {
        id: 0
      }
    };
  },

  computed: {
    //弹框标题
    dialogTitle() {
      return !this.dataForm.id ? '新增' : '编辑';
    }
  },

  methods: {
    init(id) {
      this.dataForm.id = id || 0;
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields();
        if (id) {
          //是编辑
          CategoryAPI.getCategoryDetailById(this.dataForm.id)
            .then(result => {
              this.dataForm = result.data; //看接口文档，知道data是对应的用户对象
            })
            .catch(error => {});
        } else {
          //是新增
          this.setDataFormToDefault();
        }
      });
    },

    dataFormSubmit() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          CategoryAPI.updateCategory(this.dataForm)
            .then(() => {
              this.$message.success(`保存成功`);
              this.dialogVisible = false;
              this.$emit('refreshDataList'); //重新刷新列表数据
            })
            .catch(error => {});
        }
      });
    },

    setDataFormToDefault() {
      //初始默认值
      let defaultForm = {};
      defaultForm.id = 0;
      defaultForm.name = '';
      this.dataForm = Object.assign({}, defaultForm);
    }
  }
};
</script>

<style scoped="scoped"></style>
